/* 
 * Enterprise Library Extensions - DI + ORM.
 * Copyright (C) 2006
 *
 * GNU General Public License
 *
 * This program is free software; you can redistribute 
 * it and/or modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using ELE.EnterpriseLibrary.Naming.Configuration;

namespace ELE.EnterpriseLibrary.Naming
{
  /// <summary>
  /// Custom factory for the object storage from configuration settings.
  /// </summary>
  public class NamingContextManagerCustomFactory : ICustomFactory
  {
    /// <summary>
    /// Creates an instance of <see cref="NamingContextManager"/> from configuration source.
    /// </summary>
    /// <param name="context"></param>
    /// <param name="name"></param>
    /// <param name="configurationSource"></param>
    /// <param name="reflectionCache"></param>
    /// <returns></returns>
    public object CreateObject(IBuilderContext context, string name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
    {
      NamingContextConfigurationView view = new NamingContextConfigurationView(configurationSource);
      NamingContextManager createdObject = null;
      NamingContextData contextData = view.GetContextData(name);
      if (contextData != null)
      {
        IConfigurationSource fileSource = new FileConfigurationSource(contextData.FilePath);
        // TODO: Need actual implementation based on a context factory that implements IInitialContextFactory
        INamingContext ctx = new InitialContext(contextData.FilePath);
        createdObject = new NamingContextManager(ctx);
        RegisterObject(context, name, createdObject);
      }
      return createdObject;
    }
    private void RegisterObject(IBuilderContext context, string name, NamingContextManager createdObject)
    {
      if (context.Locator != null)
      {
        ILifetimeContainer lifetime = context.Locator.Get<ILifetimeContainer>(typeof(ILifetimeContainer), SearchMode.Local);

        if (lifetime != null)
        {
          context.Locator.Add(new DependencyResolutionLocatorKey(typeof(NamingContextManager), name), createdObject);
          lifetime.Add(createdObject);
        }
      }
    }
  }

}
